import Toast from 'tdesign-miniprogram/toast/index';
import { fetchSettleDetail } from '../../../services/order/orderConfirm';
import { commitPay, wechatPayOrder } from './pay';
import { getAddressPromise } from '../../usercenter/address/list/util';
// 接口
import { fetchShopTradeInfo, fetchShopTrade, fetchScoreshopTradeInfo, fetchScoreshopTrade } from '~/request/api';

const stripeImg = `https://cdn-we-retail.ym.tencent.com/miniapp/order/stripe.png`;

Page({
  data: {
    placeholder: '备注信息',
    stripeImg,
    loading: false,
    settleDetailData: {
      storeGoodsList: [], //正常下单商品列表
      outOfStockGoodsList: [], //库存不足商品
      abnormalDeliveryGoodsList: [], // 不能正常配送商品
      inValidGoodsList: [], // 失效或者库存不足
      limitGoodsList: [], //限购商品
    }, // 获取结算页详情 data
    orderCardList: [], // 仅用于商品卡片展示
    goodsRequestList: [],
    userAddressReq: null,
    popupShow: false, // 不在配送范围 失效 库存不足 商品展示弹框
    notesPosition: 'center',
    storeInfoList: [],
    storeNoteIndex: 0, //当前填写备注门店index
    userAddress: null,
    tradeInfo: {},
    totalGoodsCount: 0,
    desc: '', // 备注
    symbol: '¥',
  },

  payLock: false,
  noteInfo: [],
  tempNoteInfo: [],
  onLoad(options) {
    console.log(options);
    this.setData({
      loading: true,
      ...options,
    });
    options?.cart_ids && this.shopTradeInfo({ cart_ids: options?.cart_ids });
    options?.goods_id && this.scoreShopTradeInfo({ goods_id: options?.goods_id })
  },
  onShow() { },

  // 购物车信息
  async shopTradeInfo(params) {
    try {
      const res = await fetchShopTradeInfo(params);
      let _total =
        res?.cart_inf?.length > 1 ? res.cart_info.reduce((total, curr) => total.num + curr.num) : res.cart_info[0].num;
      this.setData({
        userAddress: res.address_info.find((item) => item.is_def == 2),
        tradeInfo: res,
        totalGoodsCount: _total,
        loading: false,
      });
    } catch (error) {
      console.log(error);
    }
  },

  // 商品兑换信息
  async scoreShopTradeInfo(params) {
    try {
      const res = await fetchScoreshopTradeInfo(params);
      this.setData({
        userAddress: res.address_info.find((item) => item.is_def == 2),
        tradeInfo: res,
        totalGoodsCount: 1,
        loading: false,
        symbol: ''
      });
    } catch (error) {
      console.log(error);
    }
  },

  // 立即兑换
  async scoreShopTrade() {
    const { goods_id, userAddress, tradeInfo, desc } = this.data;
    let params = { goods_id, add_id: userAddress?.id, trade_no: tradeInfo.trade_no, desc };
    try {
      const res = await fetchScoreshopTrade(params);
      const payInfo = res?.pay_info ? JSON.parse(res.pay_info) : null;
      if (payInfo) {
        wx.requestPayment({
          ...payInfo,
          success: () => {
            Toast({
              context: this,
              selector: '#t-toast',
              message: '支付成功',
              duration: 2000,
              icon: '',
            });
          },
          fail: (err) => {
            console.log(err);
            Toast({
              context: this,
              selector: '#t-toast',
              message: '支付异常, 请稍后重试',
              duration: 2000,
              icon: '',
            });
          },
          complete: () => {
            wx.switchTab({
              url: '/pages/home/home',
            });
          },
        });
      } else {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '兑换成功',
          duration: 2000,
          icon: '',
        });
        wx.switchTab({
          url: '/pages/home/home',
        });
      }
    } catch (error) {
      console.log(error);
    }
  },


  init() {
    this.setData({
      loading: true,
    });
    // const { goodsRequestList } = this;
    // this.handleOptionsParams({ goodsRequestList });
  },
  // 处理不同情况下跳转到结算页时需要的参数
  handleOptionsParams(options) {
    let { goodsRequestList } = this; // 商品列表
    let { userAddressReq } = this; // 收货地址

    const storeInfoList = []; // 门店列表
    // 如果是从地址选择页面返回，则使用地址显选择页面新选择的地址去获取结算数据
    if (options.userAddressReq) {
      userAddressReq = options.userAddressReq;
    }
    if (options.type === 'cart') {
      // 从购物车跳转过来时，获取传入的商品列表数据
      const goodsRequestListJson = wx.getStorageSync('order.goodsRequestList');
      goodsRequestList = JSON.parse(goodsRequestListJson);
    } else if (typeof options.goodsRequestList === 'string') {
      goodsRequestList = JSON.parse(options.goodsRequestList);
    }
    //获取结算页请求数据列表
    const storeMap = {};
    goodsRequestList.forEach((goods) => {
      if (!storeMap[goods.storeId]) {
        storeInfoList.push({
          storeId: goods.storeId,
          storeName: goods.title,
        });
        storeMap[goods.storeId] = true;
      }
    });
    this.goodsRequestList = goodsRequestList;
    this.storeInfoList = storeInfoList;
    const params = {
      goodsRequestList,
      storeInfoList,
      userAddressReq,
    };
    fetchSettleDetail(params).then(
      (res) => {
        this.setData({
          loading: false,
        });
        this.initData(res.data);
      },
      () => {
        //接口异常处理
        this.handleError();
      },
    );
  },
  initData(resData) {
    // 转换商品卡片显示数据
    const data = this.handleResToGoodsCard(resData);
    this.userAddressReq = resData.userAddress;

    if (resData.userAddress) {
      this.setData({ userAddress: resData.userAddress });
    }
    this.setData({ settleDetailData: data });
    this.isInvalidOrder(data);
  },

  isInvalidOrder(data) {
    // 失效 不在配送范围 限购的商品 提示弹窗
    if (
      (data.limitGoodsList && data.limitGoodsList.length > 0) ||
      (data.abnormalDeliveryGoodsList && data.abnormalDeliveryGoodsList.length > 0) ||
      (data.inValidGoodsList && data.inValidGoodsList.length > 0)
    ) {
      this.setData({ popupShow: true });
      return true;
    }
    this.setData({ popupShow: false });
    if (data.settleType === 0) {
      return true;
    }
    return false;
  },

  handleError() {
    Toast({
      context: this,
      selector: '#t-toast',
      message: '结算异常, 请稍后重试',
      duration: 2000,
      icon: '',
    });

    setTimeout(() => {
      wx.navigateBack();
    }, 1500);
    this.setData({
      loading: false,
    });
  },
  getRequestGoodsList(storeGoodsList) {
    const filterStoreGoodsList = [];
    storeGoodsList &&
      storeGoodsList.forEach((store) => {
        const { storeName } = store;
        store.skuDetailVos &&
          store.skuDetailVos.forEach((goods) => {
            const data = goods;
            data.storeName = storeName;
            filterStoreGoodsList.push(data);
          });
      });
    return filterStoreGoodsList;
  },
  handleGoodsRequest(goods, isOutStock = false) {
    const { reminderStock, quantity, storeId, uid, saasId, spuId, goodsName, skuId, storeName, roomId } = goods;
    const resQuantity = isOutStock ? reminderStock : quantity;
    return {
      quantity: resQuantity,
      storeId,
      uid,
      saasId,
      spuId,
      goodsName,
      skuId,
      storeName,
      roomId,
    };
  },
  handleResToGoodsCard(data) {
    // 转换数据 符合 goods-card展示
    const orderCardList = []; // 订单卡片列表
    const storeInfoList = [];

    data.storeGoodsList &&
      data.storeGoodsList.forEach((ele) => {
        const orderCard = {
          id: ele.storeId,
          storeName: ele.storeName,
          status: 0,
          statusDesc: '',
          amount: ele.storeTotalPayAmount,
          goodsList: [],
        }; // 订单卡片
        ele.skuDetailVos.forEach((item, index) => {
          orderCard.goodsList.push({
            id: index,
            thumb: item.image,
            title: item.goodsName,
            specs: item.skuSpecLst.map((s) => s.specValue), // 规格列表 string[]
            price: item.tagPrice || item.settlePrice || '0', // 优先取限时活动价
            settlePrice: item.settlePrice,
            titlePrefixTags: item.tagText ? [{ text: item.tagText }] : [],
            num: item.quantity,
            skuId: item.skuId,
            spuId: item.spuId,
            storeId: item.storeId,
          });
        });

        storeInfoList.push({
          storeId: ele.storeId,
          storeName: ele.storeName,
          remark: '',
        });
        this.noteInfo.push('');
        this.tempNoteInfo.push('');
        orderCardList.push(orderCard);
      });

    this.setData({ orderCardList, storeInfoList });
    return data;
  },
  onGotoAddress() {
    /** 获取一个Promise */
    getAddressPromise()
      .then((address) => {
        this.handleOptionsParams({
          userAddressReq: { ...address, checked: true },
        });
      })
      .catch(() => { });

    const { userAddressReq } = this; // 收货地址

    let id = '';

    if (userAddressReq?.id) {
      id = `&id=${userAddressReq.id}`;
    }

    wx.navigateTo({
      url: `/pages/usercenter/address/list/index?selectMode=1&isOrderSure=1${id}`,
    });
  },
  onNotes() {
    // 添加备注信息
    this.setData({
      dialogShow: true,
    });
  },
  onInput(e) {
    this.setData({
      desc: e.detail.value,
    });
  },
  onBlur() {
    this.setData({
      notesPosition: 'center',
    });
  },
  onFocus() {
    this.setData({
      notesPosition: 'self',
    });
  },
  onNoteConfirm() {
    // 备注信息 确认按钮
    const { desc } = this.data;

    this.setData({
      dialogShow: false,
      desc,
    });
  },
  onNoteCancel() {
    // 备注信息 取消按钮
    this.setData({
      dialogShow: false,
      desc: '',
    });
  },

  onSureCommit() {
    // 商品库存不足继续结算
    const { settleDetailData } = this.data;
    const { outOfStockGoodsList, storeGoodsList, inValidGoodsList } = settleDetailData;
    if ((outOfStockGoodsList && outOfStockGoodsList.length > 0) || (inValidGoodsList && storeGoodsList)) {
      // 合并正常商品 和 库存 不足商品继续支付
      // 过滤不必要的参数
      const filterOutGoodsList = [];
      outOfStockGoodsList &&
        outOfStockGoodsList.forEach((outOfStockGoods) => {
          const { storeName } = outOfStockGoods;
          outOfStockGoods.unSettlementGoods.forEach((ele) => {
            const data = ele;
            data.quantity = ele.reminderStock;
            data.storeName = storeName;
            filterOutGoodsList.push(data);
          });
        });
      const filterStoreGoodsList = this.getRequestGoodsList(storeGoodsList);
      const goodsRequestList = filterOutGoodsList.concat(filterStoreGoodsList);
      this.handleOptionsParams({ goodsRequestList });
    }
  },

  // 提交结算信息
  async shopTrade() {
    const { cart_ids, userAddress, tradeInfo, desc } = this.data;
    let params = { cart_ids, pay_type: 2, add_id: userAddress?.id, trade_no: tradeInfo.trade_no, desc };
    try {
      const res = await fetchShopTrade(params);
      const payInfo = JSON.parse(res.pay_info);
      wx.requestPayment({
        ...payInfo,
        success: () => {
          Toast({
            context: this,
            selector: '#t-toast',
            message: '支付成功',
            duration: 2000,
            icon: '',
          });
        },
        fail: (err) => {
          console.log(err);
          Toast({
            context: this,
            selector: '#t-toast',
            message: '支付异常, 请稍后重试',
            duration: 2000,
            icon: '',
          });
        },
        complete: () => {
          wx.switchTab({
            url: '/pages/home/home',
          });
        },
      });
    } catch (error) {
      console.log(error);
    }
  },

  // 提交订单
  submitOrder() {
    const { userAddress, goods_id } = this.data;

    if (!userAddress) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '请添加收货地址',
        duration: 2000,
        icon: 'help-circle',
      });
      return;
    }
    if (goods_id) {
      this.scoreShopTrade();
    } else {
      this.shopTrade();
    }
  },

  // 处理支付
  handlePay(data, settleDetailData) {
    const { channel, payInfo, tradeNo, interactId, transactionId } = data;
    const { totalAmount, totalPayAmount } = settleDetailData;
    const payOrderInfo = {
      payInfo: payInfo,
      orderId: tradeNo,
      orderAmt: totalAmount,
      payAmt: totalPayAmount,
      interactId: interactId,
      tradeNo: tradeNo,
      transactionId: transactionId,
    };

    if (channel === 'wechat') {
      wechatPayOrder(payOrderInfo);
    }
  },

  hide() {
    // 隐藏 popup
    this.setData({
      'settleDetailData.abnormalDeliveryGoodsList': [],
    });
  },
  onReceipt() { },

  onGoodsNumChange(e) {
    const {
      detail: { value },
      currentTarget: {
        dataset: { goods },
      },
    } = e;
    const index = this.goodsRequestList.findIndex(
      ({ storeId, spuId, skuId }) => goods.storeId === storeId && goods.spuId === spuId && goods.skuId === skuId,
    );
    if (index >= 0) {
      // eslint-disable-next-line no-confusing-arrow
      const goodsRequestList = this.goodsRequestList.map((item, i) =>
        i === index ? { ...item, quantity: value } : item,
      );
      this.handleOptionsParams({ goodsRequestList });
    }
  },

  onPopupChange() {
    this.setData({
      popupShow: !this.data.popupShow,
    });
  },
});
